const _ = require('lodash');

const tableWidth = '';
const borderStyle = 'border: 1px solid #000';
const alignCenter = 'text-align: center';
const padding = 'padding: 3px 8px';

class Table {
    constructor(title) {
        this._title = title;
        this._header = [];
        this._rows = [];
        this._sum = 1;
        this._sumSkip = [];
    }

    header(array, color = '#409EFF') {
        this._header = array;
        this._color = color;
    }

    row(row) {
        this._rows.push(row);
    }

    sumStartAt(sum) {
        this._sum = sum;
    }

    sumSkip(skip) {
        this._sumSkip.push(skip);
    }

    toString() {
        let headers = '', rows = '', sum = {};
        this._header.forEach(header => {
            headers += `<td style="${borderStyle};${padding};">${header}</td>`;
        });
        this._rows.forEach(row => {
            let rowContent = '';
            row.forEach((row, i) => {
                rowContent += `<td style="${borderStyle};${padding};">${row}</td>`;
                if (this._sumSkip.indexOf(i) === -1) {
                    if (i >= this._sum) {
                        if (!sum[i]) {
                            sum[i] = 0;
                        }
                        if (_.isNumber(row))
                            sum[i] += row;
                    }
                } else sum[i] = '';
            });
            rows += '<tr>' + rowContent + '</tr>';
        });
        sum = Object.values(sum);
        if (this._rows.length === 0)
            _.range(this._header.length - this._sum).forEach(() => {
                sum.push('0');
            });
        sum = sum.map(s => {
            return `<td style="${borderStyle};${padding};">${s}</td>`;
        }).join('');
        return `<table style="border-collapse: collapse;${borderStyle};${tableWidth};${alignCenter};"><tbody>
<tr style="background:${this._color};color:#fff;${borderStyle};"><td style="${padding};" colspan="${headers.length}">${this._title}</td></tr>
<tr style="background:${this._color};color:#fff;${borderStyle};">${headers}</tr>
${rows}
<tr style="background:${this._color};color:#fff;${borderStyle};"><td style="${padding};" colspan="${this._sum}">总计</td>${sum}</tr>
</tbody></table>`
    }
}

module.exports = Table;